package com.blog4java.jndi;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class JndiExample {
   @Before
   public void before() throws IOException {
	  //创建数据源工厂类
	  DataSourceFactory dsf = new UnpooledDataSourceFactory();
	  Properties properties = new Properties();
	  InputStream configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties");
	  properties.load(configStream);
	  dsf.setProperties(properties);
	  DataSource dataSource = dsf.getDataSource();
      try {
    	  //设置JNDI环境属性
          Properties jndiProps = new Properties();
          jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
          jndiProps.put(Context.URL_PKG_PREFIXES, "org.apache.naming");
          //创建初始上下文
          Context ctx = new InitialContext(jndiProps);
          //绑定对象到JNDI树
          ctx.bind("java:TestDC", dataSource);
      } catch (NamingException e) {
          e.printStackTrace();
      }
   }
   
   @Test
   public void testJndi() {
       try {
           Properties jndiProps = new Properties();
           jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
           jndiProps.put(Context.URL_PKG_PREFIXES, "org.apache.naming");
           Context ctx = new InitialContext(jndiProps);
           //使用JNDI查找数据源
           DataSource dataSource = (DataSource) ctx.lookup("java:TestDC");
           Connection conn = dataSource.getConnection();
           Assert.assertNotNull(conn);
       } catch (Exception e) {
           e.printStackTrace();
       }
   } 
}
